package cleaner;

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.io.*;


/**
 *
 * @author Adyakov Denis aka DoZENT
 */
public class FileWorker {

    private class RecycleBinCleaner extends Thread{

        private String m_RecycleBinPath;

        private class OldFilesFilter implements FilenameFilter {
            public boolean accept(File dir, String name) {
                return (name.lastIndexOf("_old") == name.length()-4);
            }
        }


        RecycleBinCleaner(String pRecycleBinPath){
            m_RecycleBinPath = pRecycleBinPath;
        }

        @Override
        public void run(){
            //Clean recycle bin
            File dir = new File (m_RecycleBinPath);
            if (dir.isDirectory()){
                //Search files with _old filter
                FilenameFilter filter = new OldFilesFilter ();
                String filesList[] = dir.list(filter);
                for (int i=0; i<filesList.length;i++){
                    File newItem = new File (m_RecycleBinPath + File.separator + filesList[i]);
                    if (newItem.isFile()){
                        Date lastModifiedDate = new Date (newItem.lastModified());
                        Calendar cal1 = Calendar.getInstance();
                        Calendar cal2 = Calendar.getInstance();
                        cal2.setTime(lastModifiedDate);
                        //go 1 week back
                        cal1.add(Calendar.WEEK_OF_MONTH, -1);

                        //if file is older then 1 week then delete it
                        if (cal2.before(cal1)){
                            //delete file
                            //System.out.println("Orfile " + m_RecycleBinPath + File.separator + filesList[i].substring(0, filesList[i].length()-4));
                            if (filesList[i].length() > 4){
                                File f1 = new File (m_RecycleBinPath + File.separator + filesList[i].substring(0, filesList[i].length()-4));
                                if (f1.exists()){
                                    f1.delete();
                                }
                                //delete description of file
                                if (newItem.exists()){
                                    newItem.delete();
                                }
                            }
                        }

                    }
                    
                }
            }
        }

    }

    private class FileThread extends Thread{

        private String m_DirPath;
        private String m_RecycleBinFolder;

        private void CreateDescriptionFile (String pOriginalFilePath, String pNewFilePath){

            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy");                        
            try{
                FileWriter fstream = new FileWriter (m_RecycleBinFolder + File.separator + pNewFilePath);
                BufferedWriter bwriter = new BufferedWriter (fstream);
                bwriter.write("Original File=" + pOriginalFilePath);
                bwriter.newLine();                
                bwriter.write("Moved Date=" + sdf.format(cal.getTime()));
                bwriter.newLine();
                cal.add(Calendar.WEEK_OF_MONTH, 1);
                bwriter.write("Delete Date=" + sdf.format(cal.getTime()));
                bwriter.close();

            }
            catch (IOException ex){
                ex.getMessage();
            }

        }
        
        @Override
        public void run(){
            //Processing directory
            File dir = new File (m_DirPath);
            String filesList[] = dir.list();
            //Process every item in directory
            for (int i=0; i<filesList.length; i++){

                //Sleep some time to make processor feel better :)
                try{
                    Thread.sleep(1000);
                }
                catch (InterruptedException ex){
                    ex.printStackTrace();
                }

                //analyze next item
                File newItem = new File (m_DirPath + File.separator + filesList[i]);

                //if item is dir create separate thread for it
                if (newItem.isDirectory()){
                    System.out.println (m_DirPath + File.separator + filesList[i]);
                    Thread newFileThread = new Thread (new FileThread(m_DirPath + File.separator + filesList[i], m_RecycleBinFolder), m_DirPath);
                    newFileThread.start();
                }

                //if item is file check for it's last access date
                else if (newItem.isFile()){
                    Date lastModifiedDate = new Date (newItem.lastModified());                      
                    Calendar cal1 = Calendar.getInstance();
                    Calendar cal2 = Calendar.getInstance();                    
                    cal2.setTime(lastModifiedDate);
                    //go 1 month back
                    cal1.add(Calendar.MONTH, -1);

                    //if date of file modification is later then 1 month ago move this file to recycle bin
                    if (cal2.before(cal1)){
                        CreateDescriptionFile (newItem.getAbsolutePath(), newItem.getName() + "_old");
                        newItem.renameTo(new File(m_RecycleBinFolder, newItem.getName()));                        
                    }
                    
                }

            }


        }

        //constructor
        FileThread (String pDirPath, String pRecycleBinFolder){
            m_DirPath = pDirPath;
            m_RecycleBinFolder = pRecycleBinFolder;
        }

    }

    private String m_CurrentDir;
    private String m_RecycleBinFolder;

    /**
     * Set parameters we need
     * @param pDirPath folder to clean
     * @param pRecycleBinFolder path to recycle bin folder where files to delete will storing
     */
    public FileWorker(String pDirPath, String pRecycleBinFolder){
        m_CurrentDir = pDirPath;
        m_RecycleBinFolder = pRecycleBinFolder;
    }

    /**
     * Start to clean folder
     */
    public void CleanFolder(){

        File dir = new File (m_CurrentDir);
        if (dir.isDirectory()){
            Thread newFileThread = new Thread (new FileThread(m_CurrentDir, m_RecycleBinFolder), m_CurrentDir);
            newFileThread.start();
        }
    }

    /**
     * Start to clean recycle bin
     */
    public void CleanRecycleBin(){
        Thread newRecycleThread = new Thread (new RecycleBinCleaner(m_RecycleBinFolder), "Recycle cleaner thread");
        newRecycleThread.start();
    }

}
